package com.panshi.modules.system.controller;


import com.google.code.kaptcha.Producer;
import com.panshi.api.util.CommonResult;
import com.panshi.api.util.R;
import com.panshi.api.util.ResultConstant;
import com.panshi.api.vo.SysUserLogin;
import com.panshi.modules.system.bean.BeiSysRole;
import com.panshi.modules.system.bean.BeiSysUser;
import com.panshi.modules.system.bean.BeiSysUserRole;
import com.panshi.modules.system.service.BeiSysRoleService;
import com.panshi.modules.system.service.BeiSysUserRoleService;
import com.panshi.modules.system.service.BeiSysUserService;
import com.panshi.modules.system.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 后端管理用户  前端控制器
 * </p>
 *
 * @author 小伍
 * @since 2020-08-05
 */
@Controller
@Slf4j
@Api(tags = "系统用户登录接口")
public class BeiSysUserController {

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private BeiSysUserService beiSysUserService;

    @Autowired
    private BeiSysUserRoleService beiSysUserRoleService;

    @Autowired
    private BeiSysRoleService beiSysRoleService;


    @GetMapping(value = {"/","/login"})
    @ApiOperation("登录页面")
    public String login(){
        System.out.println("我进来了========================================");
        return "/login/login";
    }

    @GetMapping("/sys/index")
    @ApiOperation("登录之后的页面")
    @RequiresPermissions("sys:list")
    public String index(){

        return "/login/index";
    }

    @PostMapping("/login")
    @ApiOperation("系统用户登录接口")
    @ResponseBody
    public CommonResult<Object> logins(SysUserLogin sysUserLogin, HttpSession session){

        System.out.println(sysUserLogin);
        System.out.println(session.getAttribute("kaptcha"));
        CommonResult<Object> com=new CommonResult<>();
        //ResultConstant
        String kaptcha = (String)session.getAttribute("kaptcha");
        if(!(sysUserLogin.getCode().equals(kaptcha))){
            com.setCode(ResultConstant.AUTH_CODE);
            com.setMsg(ResultConstant.AUTH_MES);
            return com;
        }
        //获取当前的用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token=new UsernamePasswordToken(sysUserLogin.getUserName(),sysUserLogin.getPassword());
        try {
            subject.login(token);//执行登录的异常 如果没有异常就说明ok
            //Map<String,Object> claims = new HashMap<String, Object>();
          //  claims.put("username", token.getPassword());
           // String tokens=JwtUtil.createJwtToken(token.getUsername(),claims);
            //com.setToken(tokens);
            BeiSysUser user = (BeiSysUser) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("myuser",user);
            //session.setAttribute("time", DateUtil.date());
        }catch (UnknownAccountException e){//用户不存在
            System.out.println(111);
            com.setCode(ResultConstant.USER_CODE);
            com.setMsg(ResultConstant.ACCOUNTS_MES);
            return com;
        }catch (IncorrectCredentialsException e){
            System.out.println(1111111);
            com.setCode(ResultConstant.PASSWORD_CODE);
            com.setMsg(ResultConstant.PASSWORD_MES);
            return com;
        }
        System.out.println(222222);
        return com;
    }




    @ApiOperation("验证码")
    @RequestMapping(path = "/user/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        // 将验证码存入session
        session.setAttribute("kaptcha", text);

        // 将突图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            log.error("响应验证码失败:" + e.getMessage());
        }
    }


    @ApiOperation("返回管理员页面")
    @GetMapping("/sys/list")
   @RequiresPermissions("sys:list")
    public String  getadminlist()
    {
        return "/admin/admin-list";
    }

    @GetMapping("/sys/query")
    @ResponseBody
    @RequiresPermissions("sys:list")
    public  R querySyUser(Integer currentPage,Integer pageSize){
        Map<String,Integer> map=new HashMap<>();
        map.put("currentPage", currentPage);
        map.put("pageSize",pageSize);
        List<BeiSysUser> beiSysUsers = beiSysUserService.querySys(map);
       List<List<BeiSysRole>> list=new ArrayList<>();
        for (int i = 0; i < beiSysUsers.size(); i++) {
            List<BeiSysRole> queryall = beiSysRoleService.queryall(beiSysUsers.get(i).getUaid());
            list.add(queryall);
        }
        for (int i = 0; i < list.size(); i++) {
            beiSysUsers.get(i).setBeiSysRole(list.get(i));
        }
        System.out.println(beiSysUsers);
        Integer total=beiSysUserService.querySysUserCount();
        return  R.ok().data("data",beiSysUsers).data("total",total);
    }


    //获取初始下标
    public int getstateindex(int current,int page) {
        if(current==0) {
            return 0;
        }else {
            return page*(current-1);
        }
    }
    @GetMapping("/sys/add")
  @RequiresPermissions("sys:add")
    public String adminAdd(){
        return "/admin/admin-add";
    }

    @PostMapping("/sys/adduser")
    @RequiresPermissions("sys:add")
    @ResponseBody
    public CommonResult addSysUser(@Validated BeiSysUser beiSysUser, Integer [] checkList){
        beiSysUser.setLastLoginTime(new Date());
        int uaid = beiSysUserService.addSysUser(beiSysUser);
        for (Integer integer : checkList) {
            BeiSysUserRole beiSysUserRole=new BeiSysUserRole();
            beiSysUserRole.setUid(uaid);
            beiSysUserRole.setRid(integer);
            beiSysUserRole.setCreatedTime(new Date());
            beiSysUserRoleService.addSysUserRole(beiSysUserRole);
        }
        return new CommonResult();
    }
    @PostMapping("/sys/update")
    @RequiresPermissions("sys:update")
    @ResponseBody
    public CommonResult updateSysUser(@Validated BeiSysUser beiSysUser, Integer [] checkList){
        beiSysUserService.updateSysUser(beiSysUser);
        beiSysUserRoleService.deleteSysUserRole(beiSysUser.getUaid());
        for (Integer integer : checkList) {
            BeiSysUserRole beiSysUserRole=new BeiSysUserRole();
            beiSysUserRole.setUid(beiSysUser.getUaid());
            beiSysUserRole.setRid(integer);
            beiSysUserRole.setCreatedTime(new Date());
            beiSysUserRoleService.addSysUserRole(beiSysUserRole);
        }
        return new CommonResult();
    }

    @GetMapping("/sys/delete")
    @RequiresPermissions("sys:delete")
    @ResponseBody
    public CommonResult deleteSysUser(Integer uaid){
        beiSysUserRoleService.deleteSysUserRole(uaid);
        beiSysUserService.deleteSysUser(uaid);
        return new CommonResult();
    }

}

